package org.custom.spring.boot.mybatis.plugin.impl;

import org.apache.ibatis.executor.Executor;
import org.apache.ibatis.mapping.MappedStatement;
import org.apache.ibatis.mapping.SqlCommandType;
import org.apache.ibatis.plugin.Intercepts;
import org.apache.ibatis.plugin.Invocation;
import org.apache.ibatis.plugin.Signature;
import org.custom.spring.boot.mybatis.plugin.AbstractMybatisPlugin;
import org.custom.spring.boot.mybatis.service.plugin.algorithm.MybatisAlgorithm;
import org.custom.spring.boot.mybatis.service.plugin.algorithm.impl.MybatisOptimisticLockAlgorithm;
import org.custom.spring.boot.mybatis.service.plugin.process.MybatisProcessor;
import org.custom.spring.boot.mybatis.service.plugin.process.impl.OptimisticLockMybatisProcessor;

/**
 * Mybatis乐观锁插件
 *
 * @author LiKun
 */
@Intercepts(@Signature(type = Executor.class, method = "update", args = {MappedStatement.class, Object.class}))
public class MybatisOptimisticLockPlugin extends AbstractMybatisPlugin {
    private final MybatisProcessor mybatisProcessor = new OptimisticLockMybatisProcessor();
    private final MybatisAlgorithm mybatisAlgorithm = new MybatisOptimisticLockAlgorithm();

    @Override
    public MybatisProcessor obtainProcess() {
        return this.mybatisProcessor;
    }

    @Override
    public MybatisAlgorithm obtainMybatisAlgorithm() {
        return this.mybatisAlgorithm;
    }

    @Override
    public boolean determineWhether2Execute(Invocation invocation) {
        return SqlCommandType.UPDATE == ((MappedStatement) invocation.getArgs()[0]).getSqlCommandType();
    }
}
